package cn.sumpu.app.guoguojie.biz.impl;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
//import org.slf4j.*;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import cn.sumpu.app.guoguojie.biz.*;
import cn.sumpu.app.guoguojie.constant.*;
import cn.sumpu.app.guoguojie.dao.DoingTagDao;
import cn.sumpu.app.guoguojie.domain.*;
import cn.sumpu.app.guoguojie.exception.AppBusinessException;
import cn.sumpu.app.guoguojie.util.*;

public class DoingTagBizImpl implements DoingTagBiz, InitializingBean {

//	private static Logger logger = LoggerFactory.getLogger(DoingTagBizImpl.class);
	
	@Autowired
	private IdentifierBiz identifierBiz;
	@Autowired
	DoingTagShowBiz doingTagShowBiz;
	@Autowired
	DoingBiz doingBiz;
	@Autowired
    TopBiz topBiz;
	
	private DoingTagDao doingTagDao;
	private String etaoDir;

	public void setEtaoDir(String etaoDir) {
		this.etaoDir = etaoDir;
	}
	public void setDoingTagDao(DoingTagDao doingTagDao) {
		this.doingTagDao = doingTagDao;
	}

	// 添加标签信息
	@Override
	public void addDoingTag(DoingTag doingTag) throws AppBusinessException {
		if (Common.emptyStr(doingTag.getIdentifier())) {
			doingTag.setIdentifier(identifierBiz.generateId("doing_tag"));
		}
		doingTagDao.addDoingTag(doingTag);
	}

	// 删除标签信息
	@Override
	public void deleteDoingTagById(String tagId) throws AppBusinessException {
		doingTagDao.deleteDoingTagById(tagId);
	}

	// 取得子节点的全部ID
	private List<DoingTag> getChildrenDoingTagList(String parentId)
			throws AppBusinessException {
		List<DoingTag> list = getDoingTagList(parentId, null, null, null, null,
				null);
		for (DoingTag c : list) {
			c.setTagList(getChildrenDoingTagList(c.getIdentifier()));
		}
		return list;
	}

	private List<DoingTag> buildChildren(String parentId)
			throws AppBusinessException {
		return getChildrenDoingTagList(parentId);
	}

	@Override
	public String getChildrenCategoryId(String parentId)
			throws AppBusinessException {
		List<String> categoryBuilder = new ArrayList<String>();
		return "(" + getCategory(parentId, categoryBuilder) + ")";
	}

	private String getCategory(String id, List<String> list)
			throws AppBusinessException {
		List<DoingTag> cList = buildChildren(id);
		for (DoingTag tmp : cList) {
			list.add("'" + tmp.getIdentifier() + "'");
			List<DoingTag> children = tmp.getTagList();
			if (null != children && children.size() > 0) {
				getCategory(tmp.getIdentifier(), list);
			}
		}
		StringBuilder s = new StringBuilder();
		for (String tmp : list) {
			s.append(tmp + ",");
		}
		s.append("'" + id + "'");
		return s.toString();
	}

	// 删除标签(包括子类)
	@Override
	public void deleteDoingTagAll(String tagId) throws AppBusinessException {
		// 取得全部子节点（包括自己）
		String identifierList = getChildrenCategoryId(tagId);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("identifier", identifierList);
		doingTagDao.deleteDoingTagAll(map);
	}

	// 更新标签信息
	@Override
	public void updateDoingTagById(DoingTag doingTag)
			throws AppBusinessException {
		doingTagDao.updateDoingTagById(doingTag);
	}

	// 取得标签列表
	@Override
	public List<DoingTag> getDoingTagList(String parentId, String name,
			Integer deep, Boolean enabled, String identifier, Integer isDisplay)
			throws AppBusinessException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("parentIdentifier", parentId);
		map.put("name", name);
		map.put("deep", deep);
		map.put("enabled", enabled);
		map.put("identifier", identifier);
		map.put("isDisplay", isDisplay);
		return doingTagDao.getDoingTagList(map);
	}

	// 取得所有标签
	@Override
	public List<DoingTag> getDoingTagAll(String parentId)
			throws AppBusinessException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("parentIdentifier", parentId);
		return doingTagDao.getDoingTagAll(map);
	}

	// 给微博的产品打上标签
	@Override
	public String pasteTagDoing(DoingProduct product, String doingId)
			throws AppBusinessException {
		// 匹配到标签的集合
		ArrayList<DoingTag> l = new ArrayList<DoingTag>();
		//权重标签集合
		List<DoingTag> weightList = new ArrayList<DoingTag>();
		// 取得所有标签名称
		List<DoingTag> tags = DoingTag.doingTagName;
		DoingTag tag = null;
		// 标签名称
		String tagName = "";
		//权重最高
		if(weightList.size()==0){
			if(product.getName().toUpperCase()
					.contains("孕妇")){
				weightList.add(new DoingTag("100001330","孕产必备"));
			}
		}
		for (int i = 0; i < tags.size(); i++) {
			tag = tags.get(i);
			if (product.getName().toUpperCase()
					.contains(tag.getName().toUpperCase())) {
				// ///////////////加入匹配集合
				l.add(tag);
			}
		}
		if (l.size() <= 0)
			return null;
		// //////////////////////////计算标签
		if(weightList.size()==0){
			if (l != null) {
				for (int i = 0; i < l.size(); i++) {
					DoingTag d = l.get(i);
					DoingTag pd = getDoingTagSelfAndParent(d.getIdentifier());
					while (pd.getDoingTag() != null) {
						pd = pd.getDoingTag();
					}
					if(pd.getType()!=2){
						if (weightList.contains(pd)) {
							pd.setWeight(pd.getWeight() + 1);
						} else {
							pd.setWeight(1);
							weightList.add(pd);
						}
					}
					// 打印匹配到的所有标签
//					System.out.println(pd.getName() + "+++++++++" + d.getName());
				}
			}
			// 删除权重低的标签
			for (int i = 0; i < weightList.size(); i++) {
				for (int j = 0; j < weightList.size(); j++) {
					if (i == j) {
						continue;
					}else if (weightList.get(i).getWeight() > weightList.get(j)
							.getWeight()) {
						weightList.remove(j);
					} else if (weightList.get(i).getWeight() < weightList.get(j)
							.getWeight()) {
						weightList.remove(i);
					}
				}
			}
		}
//		for (DoingTag t : weightList) {
//			// 打印计算后的标签大类
//			System.out.println(t.getName() + "----------" + t.getWeight());
//		}
		// 开始打标签
		for (DoingTag d : l) {
			DoingTag pd = getDoingTagSelfAndParent(d.getIdentifier());
			while (pd.getDoingTag() != null && pd.getDeep() != 1) {
				pd = pd.getDoingTag();
			}
			// 打上计算后的标签
			if (weightList.contains(pd) || pd.getType()==2) {
				// 打标签时同时打上父类
				tagName += getSelf(d.getIdentifier()) + ",";
				// 打印没重复的标签
//				System.out.println("最终标签：" + d.getName());
			}
		}
		List<String> list = new ArrayList<String>();
		// 去除重复的标签
		if (tagName.length() > 0) {
			String[] tagArr = tagName.split(",");
			for (int i = 0; i < tagArr.length; i++) {
				if (!list.contains(tagArr[i])) {
					list.add(tagArr[i]);
				}
			}
		}
		tagName = "";
		for (int i = 0; i < list.size(); i++) {
			if (i == list.size() - 1) {
				tagName += list.get(i);
			} else {
				tagName += list.get(i) + ",";
			}
		}
		String[] tagArr = tagName.split(",");
		for (String tagStr : tagArr) {
			doingTagDao.addDoingSystemTag(new DoingSystemTag(doingId, tagStr));
		}
		return tagName;
	}

	// 新的标签
	private String getSelf(String identifier) throws AppBusinessException {
		DoingTag tag = getDoingTagSelfAndParent(identifier);
		String name = "";
		while (tag != null) {
			name += tag.getIdentifier() + ",";
			tag = tag.getDoingTag();
		}
		if (name.length() > 0) {
			name = ",".equals(name.substring(name.length() - 1)) ? name
					.substring(0, name.length() - 1) : name;
		}
		return name;
	}

	// 根据ID取得标签及所有上级标签
	@Override
	public DoingTag getDoingTagSelfAndParent(String identifier)
			throws AppBusinessException {
		return doingTagDao.getDoingTagSelfAndParent(identifier);
	}

	// 取得所有标签名称
	@Override
	public List<DoingTag> getDoingTagName() throws AppBusinessException {
		return doingTagDao.getDoingTagName();
	}

	// 容器启动时加载标签
	@Override
	public void afterPropertiesSet() {
		try{
	        //定时器
	        Timer timer = new Timer();
	        //设置时间(每天的一点钟生成文件)
	        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	        Date date = new Date();
	        date = sdf.parse(sdf.format(date));
	        date = new Date(date.getTime() + (1000 * 60 * 60 * 24) + (1000*60*60));
	        //定时执行此任务
	        timer.schedule(new EtaoTask(), date, 1000 * 60 * 60 * 24);
		}catch(Exception e){
		    e.printStackTrace();
		}
	}

	// 给指定的微博打标签
	public void printTag(Doing doing) {
		try {
			List<DoingTag> weightList = new ArrayList<DoingTag>();
			if (doing != null && doing.getDoingProductList() != null
					&& doing.getDoingProductList().size() > 0) {
				// 匹配到标签的集合
				ArrayList<DoingTag> l = new ArrayList<DoingTag>();
				// 取得所有标签名称
				List<DoingTag> tags = DoingTag.doingTagName;
				DoingTag tag = null;
				// 标签名称
				String tagName = "";
				for (DoingProduct p : doing.getDoingProductList()) {
					//权重最高
					if(weightList.size()==0){
						if(p.getName().toUpperCase()
								.contains("孕妇")){
							weightList.add(new DoingTag("100000519","孕产必备"));
						}else if(p.getName().toUpperCase()
								.contains("童装")){
							weightList.add(new DoingTag("100000158","童装配饰"));
						}
					}
					for (int i = 0; i < tags.size(); i++) {
						tag = tags.get(i);
						if (p.getName().toUpperCase()
								.contains(tag.getName().toUpperCase())) {
							// ///////////////加入匹配集合
							l.add(tag);
						}
					}
				}
				if (l==null || l.size() <= 0)
					return;
				// //////////////////////////计算标签
				if(weightList.size()==0){
					for (int i = 0; i < l.size(); i++) {
						DoingTag d = l.get(i);
						DoingTag pd = getDoingTagSelfAndParent(d
								.getIdentifier());
						while (pd.getDoingTag() != null && pd.getDeep() != 1) {
							pd = pd.getDoingTag();
						}
						if(pd.getType()!=2){
							if (weightList.contains(pd)) {
								pd = getValue(weightList, pd.getIdentifier());
								pd.setWeight(pd.getWeight() + 1);
							} else {
								pd.setWeight(1);
								weightList.add(pd);
							}
						}
					}
					// 删除权重低的标签
					for (int i = 0; i < weightList.size(); i++) {
						for (int j = 0; j < weightList.size(); j++) {
							if (i == j) {
								continue;
							} else if (weightList.get(i).getWeight() > weightList
									.get(j).getWeight()) {
								weightList.remove(j);
							} else if (weightList.get(i).getWeight() < weightList
									.get(j).getWeight()) {
								weightList.remove(i);
							}
						}
					}
				}
				// 开始打标签
				for (DoingTag d : l) {
					DoingTag pd = getDoingTagSelfAndParent(d.getIdentifier());
					while (pd.getDoingTag() != null && pd.getDeep() != 1) {
						pd = pd.getDoingTag();
					}
					// 打上计算后的标签
					if (weightList.contains(pd) || pd.getType()==2) {
						// 打标签时同时打上父类
						tagName += getSelf(d.getIdentifier()) + ",";
					}
				}
				List<String> list = new ArrayList<String>();
				// 去除重复的标签
				if (tagName.length() > 0) {
					String[] tagArr = tagName.split(",");
					for (int i = 0; i < tagArr.length; i++) {
						if (!list.contains(tagArr[i])) {
							list.add(tagArr[i]);
						}
					}
				}
				tagName = "";
				for (int i = 0; i < list.size(); i++) {
					if (i == list.size() - 1) {
						tagName += list.get(i);
					} else {
						tagName += list.get(i) + ",";
					}
				}
				String[] tagArr = tagName.split(","); 
				for (String tagStr : tagArr) {
					doingTagDao.addDoingSystemTag(new DoingSystemTag(doing
							.getIdentifier(), tagStr));
				}
			}
		} catch (Exception e) {
//			System.out.println("doingId为：" + doing.getIdentifier());
			e.printStackTrace();
		}
	}

	// 从list取出对应的值
	private DoingTag getValue(List<DoingTag> list, String tagId) {
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).getIdentifier().equals(tagId)) {
				return list.get(i);
			}
		}
		return null;
	}

	// 订正标签
	@Override
	public void updateDoingSystemTagAll() throws AppBusinessException {
		int pageSize = 100; //一次取100条记录 
		int page = 1;
		Map<String, Object> map = new HashMap<String, Object>();
		// 微博总记录数
		int doingCount = doingTagDao.getDoingCount();
		int pageCount = (doingCount + pageSize - 1) / pageSize;
		for (int i = 0; i < pageCount; i++) {
			map.put("start", (page-1)*pageSize);
			map.put("pageSize", pageSize);
			List<Doing> dList = doingTagDao.getDoing(map);
			for(int j=0; j<dList.size(); j++){
				Doing d = dList.get(j);
				printTag(d);
			}
			page++;
		}
//		Map<String, Object> map = new HashMap<String, Object>();
//		// 微博总记录数
//		int doingCount = doingTagDao.getDoingCount();
//		for (int i = 0; i < doingCount; i++) {
//			map.put("start", i);
//			map.put("pageSize", 1);
//			printTag(doingTagDao.getDoing(map).get(0));
//		}
	}

	
	/**
	 * author BruceZhang
	 * 
	 * @param map
	 *            标签ID/时间
	 * @return 根据标签取得当天分享的微博
	 * @throws AppBusinessException
	 */
	@Override
	public long getTodayDoingByTagId(Date startTime, Date endTime)
			throws AppBusinessException {
		long count = 0;
		try{
			List<DoingTagShow> fTags = new ArrayList<DoingTagShow>();
			List<DoingTagShow> sTags = new ArrayList<DoingTagShow>();
			List<Etao> fList = Etao.getList();
			StringBuilder sb = new StringBuilder(""); 
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if(Common.empty(startTime) || Common.empty(endTime)){
				//昨天
				endTime = new Date();
				startTime = new Date(endTime.getTime() - (1000 * 60 * 60 * 24));
			}
			Date st = sdf.parse(sdf.format(startTime));
			Date et = sdf.parse(sdf.format(endTime));
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("channel", Grid.channel);
			map.put("startTime", st);
			map.put("endTime", et);
			map.put("startId", 0);
			map.put("pageSize", 100);
			//profile code
			long start = System.currentTimeMillis();
			for (Etao e : fList) {
				fTags = doingTagShowBiz.getDstByParentId(e.getfChannel());
				sTags = doingTagShowBiz.getDstByParentId(e.getsChannel());
				for(DoingTagShow dts : fTags){
					for(DoingTagShow dts2 : sTags){
						map.put("tagId", dts.getBackTag());
						map.put("tag2", dts2.getBackTag());
						List<Doing> dl = doingTagDao.getTodayDoingByTagId(map);
						for(Doing d : dl){
							List<DoingProduct> pl = d.getDoingProductList();
							//只推荐微博里有一个商品的
							if (pl.size() == 1) {
								count++;
								sb.append(pl.get(0).getName()).append("").append(pl.get(0).getPrice())
										.append("").append(pl.get(0).getPicUrl()).append("").append(d.getContent().replace("\n", " ").replace("\r", " "))
										.append("").append(d.getLoveAmount()).append("").append(dts.getName()).append(",").append(dts2.getName())
										.append("").append(pl.get(0).getLinkUrl()) 
										.append("").append("http://www.guoguojie.com/dt.htm?pro=").append(pl.get(0).getIdentifier())
										.append("").append(s.format(pl.get(0).getGmtCreated())).append("").append(e.getEtaoChannel()+"\r\n");
							}
						}
					}
				}
			}
			System.err.println("build data: "+(System.currentTimeMillis()-start));
			//写入数据
			start = System.currentTimeMillis();
			if(!new File(etaoDir).exists()){
				new File(etaoDir).mkdirs();
			}
			String filePath = etaoDir + "etaodata." + DateUtil.getYesterday() + ".txt";
			if(startTime!=null && endTime!=null){
				filePath = etaoDir + "etaodata." + DateUtil.getToday(startTime) + ".txt";
			}
			File f = new File(filePath);
			if(!f.exists()){
				f.createNewFile();
			}
			FileOutputStream fos = new FileOutputStream(filePath);
			OutputStreamWriter osw = new OutputStreamWriter(fos);
			BufferedWriter bw = new BufferedWriter(osw);
			bw.write(sb.toString());
			bw.close();
			osw.close();
			fos.close();
			System.err.println("write data: "+(System.currentTimeMillis()-start));
		}catch(Exception e){
			e.printStackTrace();
		}
		return count;
	}

	/**
	 * author BruceZhang
	 * 
	 * @param map
	 *            标签ID/时间
	 * @return 根据标签取得当天分享的微博总记录数
	 * @throws AppBusinessException
	 */
	@Override
	public int getTodayDoingCountByTagId(String tagId, Date startTime,
			Date endTime) throws AppBusinessException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("tagId", tagId);
		map.put("startTime", startTime);
		map.put("endTime", endTime);
		return doingTagDao.getTodayDoingCountByTagId(map);
	}
	
	class EtaoTask extends TimerTask{

		@Override
		public void run() {
			try {
				getTodayDoingByTagId(null, null);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}
	//订正标签ID
	@Override
	public List<DoingTag> getDts(int start) throws AppBusinessException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("start", start);
		return doingTagDao.getDts(map);
	}

	@Override
	public int getDtCount() throws AppBusinessException {
		return doingTagDao.getDtCount();
	}

	@Override
	public void updateDtId(String newId, String oldId)
			throws AppBusinessException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("newId", newId);
		map.put("oldId", oldId);
		doingTagDao.updateDtId(map);
	}

	@Override
	public void updateDtPid(String newId, String oldId)
			throws AppBusinessException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("newId", newId);
		map.put("oldId", oldId);
		doingTagDao.updateDtPid(map);
	}

	@Override
	public void dingZheng() {
		try {
			int count = getDtCount();
			for(int i=0; i<count; i++){
				DoingTag dt = getDts(i).get(0);
				String newId = identifierBiz.generateId("doing_tag");
				updateDtId(newId, dt.getIdentifier());
				updateDtPid(newId, dt.getIdentifier());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * author BruceZhang
	 * @param date	日期
	 * @return	返回果果街提供给一淘的数据
	 * @throws AppBusinessException
	 */
	@Override
	public String getEtaoData(String date) throws AppBusinessException {
		if(Common.emptyStr(date)){
			date = etaoDir + DateUtil.getYesterday()+".txt";
		}else{
			date = etaoDir + date + ".txt";
		}
		if(!new File(date).exists()){
			return "";
		}
		String data = HandleFile.readFileContent(date);
		return data;
	}
	//查询所有商品
	@Override
	public long getProductAll(String startTime, String endTime, String channel, String pictorial)
			throws Exception {
		long count = 0;
		StringBuilder sb = new StringBuilder("");
		SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//			Date st = sdf.parse(startTime);
//			Date et = sdf.parse(endTime);
//			Map<String, Object> map = new HashMap<String, Object>();
//			map.put("startTime", st);
//			map.put("endTime", et);
//			List<DoingProduct> dp = doingTagDao.getProductAll(map); 
		List<DoingProduct> dp = doingBiz.getProductByPictorial(startTime, endTime, pictorial);
//		doingBiz.getProductByPictorial("2012-7-1", "2012-7-27", "100038522");
		if(dp != null)
		for(DoingProduct p : dp){
			sb.append(p.getName()).append("").append(p.getPrice())
			.append("").append(p.getPicUrl()).append("").append(p.getLinkUrl()) 
			.append("").append("http://www.guoguojie.com/dt.htm?pro=").append(p.getIdentifier())
			.append("").append(s.format(p.getGmtCreated())).append("").append(channel+"\r\n");
		}
		//写入数据
		if(!new File(etaoDir).exists()){
			new File(etaoDir).mkdirs();
		}
		String filePath = etaoDir + "/etaodata." + DateUtil.getToday(sdf.parse(startTime)) + ".txt";
		File f = new File(filePath);
		if(!f.exists()){
			f.createNewFile();
		}
		FileOutputStream fos = new FileOutputStream(filePath);
		OutputStreamWriter osw = new OutputStreamWriter(fos);
		BufferedWriter bw = new BufferedWriter(osw);
		bw.write(sb.toString());
		bw.close();
		osw.close();
		fos.close();
		if(dp != null && dp.size()>0){
			count = dp.size();
		}
		return count;
	}

}
